# coding=utf-8
from model import Voucher, SeckillVoucher, VoucherOrder
from exts import db
from setting import Prefixs
from flask import request
from utils.redis import Redis

import json

from utils.def_errors import SqlExecError


def get_error(form):
    return ",".join([item[1][0] for item in form.errors.items()])


seckill_script = ""
with open('lua_script/seckill.lua', 'r', encoding='utf-8') as file:
    seckill_script = file.read()


def queryUserCache():  # 从redis查询用户信息
    token_key = Prefixs.user_token_prefix + request.headers.get("Authorization", default='')
    # 获取用户缓存
    user = Redis.hgetall(token_key)
    return user


class VoucherHelper(object):  # 处理优惠券相关

    @classmethod
    def addVoucher(cls, shopID, title, subTitle, rules, payValue, actualValue, type, status):
        voucher = Voucher(shopID=shopID, title=title, subTitle=subTitle, rules=rules, payValue=payValue,
                          actualValue=actualValue, type=type, status=status)
        db.session.add(voucher)
        db.session.commit()

    @classmethod
    def addSeckillVoucher(cls, stock, beginTime, endTime, shopID, title, subTitle, rules, payValue,
                          actualValue, type, status):
        try:
            voucher = Voucher(shopID=shopID, title=title, subTitle=subTitle, rules=rules, payValue=payValue,
                              actualValue=actualValue, type=type, status=status)
            db.session.add(voucher)
            db.session.flush()  # 此时为预提交状态 voucher.id 已经有值了
            seckill_voucher = SeckillVoucher(voucherID=voucher.id, stock=stock,
                                             beginTime=beginTime, endTime=endTime)
            db.session.add(seckill_voucher)
            db.session.commit()
            # 保存信息到redis缓存
            Redis.set(Prefixs.seckill_voucher_stock_prefix + str(seckill_voucher.voucherID),
                      json.dumps(seckill_voucher.to_dict()))
        except Exception as e:
            print(e)
            db.session.rollback()

    @classmethod
    def voucher_order_create(cls, userID, voucherID, order_id):
        # 没有订单就减少库存，生成订单表
        result = db.session.execute(
            "UPDATE tb_seckill_voucher SET stock = stock -1 where voucher_id = :voucherID and stock >= 1",
            {'voucherID': voucherID})
        if not result.rowcount:  # 如果没有更新任何数据，说明库存没有减少，订单也不能生成
            raise SqlExecError("sql更新秒杀券库存失败")
        # voucher.stock -= 1
        # 创建订单
        voucher_order = VoucherOrder(id=order_id, userID=userID, voucherID=voucherID)
        return voucher_order
